/**
 * Created by bdbs on 2017/6/20.
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
import authentication from '../components/HOC/authentication';
import style from '../style.scss';
import { host } from '../config';
import qs from 'qs';

function checkBorderRight(clentX) {
  const searchWidth = 200;
  const windowWidth = window.innerWidth;
  return windowWidth - clentX > searchWidth ? clentX : windowWidth - searchWidth;
}

function checkBorderTop(clentY) {
  const searchHeight = 200;
  const windowHeight = window.innerHeight;
  const top = windowHeight - clentY > searchHeight ? 0 : searchHeight;
  return `translate3d(0 , -${top}px, 0)`;
}

const addToNoteBook = function (selection, callback) {
  ((factory) => {
    if (!window.zzeng.videoId) {
      axios.get(host + '/uservideo/getid', {
        params: {
          videoHash: window.zzeng.fileHash,
          subtitleHash: window.zzeng.subtitleHash,
          title: window.zzeng.fileName,
        },
      }).then((res) => {
        // 如果是新创建的,同时把字幕也更新掉
        if (res.data.data.new) {
          axios.post(host + '/uservideo/uploadsubtitle', qs.stringify({
            id: res.data.data.id,
            subtitle: JSON.stringify(window.zzeng.subtitle),
          }))
        }
        window.zzeng.videoId = res.data.data.id;
        factory(window.zzeng.videoId);
      })
      return;
    }
    factory(window.zzeng.videoId);
    // factory(7);
  })((userVideoId) => {
    // if (!selection) {
    //   cacheSelection();
    // }
    const wordData = {
      userVideoId,
      did: '',
      originWord: selection.text,
      word: this.refs.wordInput.value,
      sentence: selection.sentence,
      sourceType: 'VIDEO',
    };

    axios.post(host + '/word/add', qs.stringify(wordData)).then((res) => {
      console.log('word add:', res);
      callback && callback(res);
    })
  })
}

class Dicitonary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.selection.text,
    };

    this.clearSearch = this.clearSearch.bind(this);
  }

  componentDidMount() {
    setTimeout(() => {
      document.addEventListener('click', this.clearSearch);
    })
  }

  search(word) {
    fetch(`${host}/dict?word=${this.refs.wordInput.value}&json=1`).then((response) => {
      return response.json();
    }).then((json) => {
      console.log(json);
      this.setState({
        status: 'success',
        wordData: json.dict.word || json.dict.relatedWords[0],
      });
    });
  }

  clearSearch(e) {
    if (!this.refs.searchBox || !this.refs.searchBox.contains(e.target)) {
      // this.props.clearSelection();
      document.removeEventListener('click', this.clearSearch);
    }
  }

  handleWordInput() {
    this.setState({
      value: this.refs.wordInput.value,
    });
  }

  handleAdd() {
    console.log('handleAdd');
    // this.props.checkLogin().then((res) => {
    //   addToNoteBook();
    // })
  }

  render() {
    const { wordData } = this.state;
    const { selection } = this.props;
    console.log('selection', selection);
    return (
      <div ref="searchBox" className={style.searchWBox} style={{ top: selection.clientY, left: checkBorderRight(selection.clientX), transform: checkBorderTop(selection.clientY)}}>
        <form id="wordSearch">
          <input ref="wordInput" type="text" value={this.state.value}
                 onChange={this.handleWordInput.bind(this)}/>
          <a onClick={this.search.bind(this)} className="dictSearch">Search</a>
          <a onClick={this.handleAdd.bind(this, selection)} className="addTo">Add</a>
        </form>
        { !!wordData && (
          <div>
            <h3>{ wordData.word }</h3>
            {!!wordData && (
              <div>
                <div dangerouslySetInnerHTML={{ __html:  wordData.prons }} />
                <div dangerouslySetInnerHTML={{ __html:  wordData.meaning }} />
                <div dangerouslySetInnerHTML={{ __html:  wordData.centence }} />
              </div>
            )}
          </div>
        )}
      </div>
    );
    // switch (this.state.status) {
    //   case 'success':
    //     return (
    //       <div ref="searchBox" className={style.searchWBox} >
    //         <form id="wordSearch">
    //           <input ref="wordInput" type="text" value={this.state.wordData.word} onChange={this.handleWordInput.bind(this)}/>
    //           <a className="dictSearch">Search</a>
    //           <a onClick={ addToNoteBook.bind(this, this.props.word) } className="addTo">Add</a>
    //         </form>
    //       </div>
    //     );
    //     break;
    //   default:
    //     return (<div>数据加载中...</div>);
    // }
  }
}

export default authentication(Dicitonary);
